<?php

namespace App\Models;

use App\Models\Customer;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    use HasFactory;

    protected $fillable = ['order_date','time_slot','tea','customer_id','participants','avg_cost','book_by','comment','conclusion','status','create_by'];

    public function customer(){
        return $this->belongsTo(Customer::class);
    }

    public function rooms(){
        return $this->belongsToMany(Room::class,'order_rooms','order_id','room_id');
    }

    public function user(){
        return $this->belongsTo(User::class,'create_by');
    }

    public static function dataSave($data,$user){
        $id = $data['id'];
        // 开始处理具体数据
        $order['order_date'] = Carbon::createFromFormat('Y-m-d',$data['order_date'],'Asia/Shanghai');
        $order['time_slot'] = $data['time_slot'];
        $order['tea'] = $data['tea'];
        $order['participants'] = $data['participants'];
        $order['avg_cost'] = $data['avg_cost'];
        $order['book_by'] = $data['book_by'];
        $order['comment'] = $data['comment'];
        $order['conclusion'] = $data['conclusion'];
        $order['name'] = $data['name'];
        if (key_exists('status',$data)){
            $order['status'] = $data['status'];
        }
        $order['create_by'] = $user->id;
        if($data['phone'] == '-'){
            $order['customer_id'] = null;
        }else{
            $customer = Customer::getByPhone($data['phone'],$data['name']);
            $order['customer_id'] = $customer->id;
        }

        if($id){
            self::query()->where('id',$id)->update($order);
            $result = self::query()->find($id);
        }else{
            $result = self::create($order);
        }
        // 保存完result之后保存房间信息
        $rooms = $data['rooms'];
        OrderRoom::query()->where('order_id',$result->id)->delete();
        foreach ($rooms as $room){
            OrderRoom::create([
                'order_id' => $result->id,
                'room_id'=>$room
            ]);
        }

        return $result;

    }
}
